<?php

function get_ip(){
    //判断服务器是否允许$_SERVER
    if(isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    }else{
        //不允许就使用getenv获取
        if(getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv( "HTTP_X_FORWARDED_FOR");
        }elseif(getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        }else{
            $realip = getenv("REMOTE_ADDR");
        }
    }

    return $realip;
}

class NewretailaliauthController extends Controller
{
    public function actionAliLogin()
    {
        //app()->aliUser->logout();
        $callback_landing = app()->request->getParam('callback_landing', '');
        $post_data = app()->request->getParam('post_data', '');
        $sessionId = app()->request->getParam('sessionId', '');

        return app()->NewretailAliInterface->oAuthLogin(
            aUrl('/newretailaliauth/authcallback'),
            array(
                'callback_landing' => $callback_landing,
                'sessionId' => $sessionId,
                'post_data' => $post_data,
            )
        );
    }

    public function actionAliLogout()
    {
        app()->aliUser->logout();
    }

    public function actionAuthcallback()
    {

        $auth_code = app()->request->getParam('auth_code', '');
        $state = app()->request->getParam('state', '');
        if($stateValue = app()->NewretailAliInterface->getOauth2State($state)){
            $res = app()->NewretailAliInterface->getOauth2AccessToken($auth_code);

            if($res !== false){

                $dbUser = NewretailUser::model()->findByAttributes(array(
                    'alipay_userid' => $res->alipay_user_id,
                ));

                if(empty($dbUser)){
                    $dbUser = new NewretailUser();
                    $dbUser->alipay_userid = $res->alipay_user_id;
                    $dbUser->ali_userid = $res->user_id;
                    $dbUser->create_time = date('Y-m-d H:i:s');
                    $dbUser->save(false);
                }

                $sessionId = isset($stateValue->sessionId)? $stateValue->sessionId : null;

                session_destroy();
                app()->aliUser->authLogin($dbUser, $sessionId);

                return $this->render('authcallback', array(
                    'callback_url' => $stateValue->callback_landing.'?sessionId='.$sessionId,
                    'post_data' => json_decode($stateValue->post_data, true),
                ));
            }
        }
        return $this->render('error', array(
            'message' => '不好意思，出了点小问题 :(',
        ));
    }

    public function accessRules()
    {
        return array(
            array(
                'allow',
                'actions' => array('alilogin', 'alilogout', 'authcallback'),
                'expression' => 'app()->user->anyone'
            ),

            array(
                'deny',	//should be 'deny', 'allow' is used to give convenient to make test
                'users' => array('*'),
                'redirect' => '/user/login'
            )
        );
    }
}
